import dash
import time
from dash import html, dcc
from datetime import datetime
import feffery_antd_components as fac
from dash.dependencies import Input, Output, State

app = dash.Dash(__name__)

app.layout = html.Div(
    [

        # 注入store记录最近一次点击事件
        dcc.Store(id='last-calculate-timestamp'),

        # 注入频繁任务操作提示
        html.Div(id='short-wait-message'),

        fac.AntdButton(
            '获取计算结果',
            id='calculate',
            type='primary'
        ),
        fac.AntdDivider(isDashed=True),
        fac.AntdSpin(
            html.Div(
                id='result',
                style={
                    'height': '400px'
                }
            ),
            text='计算中',
            delay=200
        )
    ],
    style={
        'padding': '50px'
    }
)


@app.callback(
    [Output('result', 'children'),
     Output('last-calculate-timestamp', 'data'),
     Output('short-wait-message', 'children')],
    Input('calculate', 'nClicks'),
    State('last-calculate-timestamp', 'data'),
)
def debounce_demo(nClicks, last_calculate_timestamp):
    # 若last_calculate_timestamp不为空
    if last_calculate_timestamp:
        # 比较距离上次执行的时间差是否大于预设值，比如10秒
        time_delta = datetime.now() - datetime.strptime(last_calculate_timestamp, '%Y-%m-%d %H:%M:%S')
        # 若距离上次任务执行已超过10秒
        if time_delta.total_seconds() >= 10:
            # 刷新last_calculate_timestamp
            last_calculate_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        # 否则不执行本次计算任务，并在前端返回信息提示告知用户剩余等待时长
        else:
            return [
                dash.no_update,
                dash.no_update,
                fac.AntdMessage(
                    type='warning',
                    content=f'距离上次计算时间过短，为了系统安全，请等待{round(10 - time_delta.total_seconds(), 1)}秒后再尝试！'
                )
            ]

    else:
        # 否则初始化last_calculate_timestamp
        last_calculate_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    if nClicks:
        time.sleep(1)

        return f'第{nClicks}次点击对应的计算结果', last_calculate_timestamp, None

    return dash.no_update


if __name__ == '__main__':
    app.run_server(debug=True)
